package com.smartkey.ui;

import java.util.ArrayList;

import com.project.smartkey.R;
import com.smartkey.adapter.AppListAdapter;
import com.smartkey.bean.AppInfo;
import com.smartkey.utils.AppUtil;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**
 * 手机安装应用列表页面
 *
 */
public class AppListActivity extends Activity{
	private ListView listview;
	private ArrayList<AppInfo> appList;
	private AppListAdapter adapter ;
	private Myhandler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_list_layout);
		
		handler = new Myhandler();
		initView();
		new Thread(){
			public void run() {
				initData();
				handler.sendEmptyMessage(0);
			};
		}.start();
		
	}

	
	class Myhandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			showApplist();//加载显示app数据
		}
	}
	
	private void initView() {
		listview = (ListView) findViewById(R.id.app_list_listview);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String checkAppPackageName = appList.get(arg2).packageName;
				System.out.println("########### AppListActivity#####  checkAppPackageName = "+checkAppPackageName);
				setReturnData(checkAppPackageName);
			}
		});
	}
	
	private void initData() {
		appList = (ArrayList<AppInfo>) AppUtil.getNonSystemAppInfo(this);
	}
	private void showApplist() {
		if(appList!=null){
			if(adapter==null){
				adapter = new AppListAdapter(this, appList);
				listview.setAdapter(adapter);
			}
			else{
				adapter.resetData(appList);
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	private void setReturnData(String packageName) {
		Intent intent = new Intent(this, MainActivity.class);
		Bundle bl = new Bundle();
		intent.putExtra("PackageName", packageName);
		setResult(MainActivity.GET_APP_OK,intent); 
		finish();
	}
	
}
